package com.example.stock.controller;

import com.example.stock.controller.dto.NorthBoundRatioDTO;
import com.example.stock.model.NorthBoundRatio;
import com.example.stock.model.WeekDetail;
import com.example.stock.service.NorthBoundService;
import com.example.stock.service.WeekDataService;
import com.example.stock.util.DateUtil;
import com.example.stock.util.Result;
import com.example.stock.util.ResultGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


@CrossOrigin(origins = "*")
@RequestMapping("northBound")
@RestController
public class NorthBoundController {

    @Autowired
    NorthBoundService northBoundService;

    @Autowired
    WeekDataService weekDataService;

    private String dateFormat(WeekDetail weekDetail) {
        String date = weekDetail.getDate();
        return date.substring(0, 4) + ":" + date.substring(date.length() - 10);
    }

    @GetMapping("ratio/{stock}")
    Result ratio(@PathVariable String stock) {
        List<NorthBoundRatio> northBoundRatios = northBoundService.getNorthBoundRatioByStock(stock);

        // 获取当时的收盘价格
        List<WeekDetail> weekRawData = weekDataService.getWeekRawData(stock);
        Map<String, Double> closeMap = weekRawData.stream().collect(Collectors.toMap(this::dateFormat, WeekDetail::getClose));

        List<NorthBoundRatioDTO> ret = new ArrayList<>();
        northBoundRatios.forEach(item -> {
            NorthBoundRatioDTO northBoundRatioDTO = new NorthBoundRatioDTO();
            BeanUtils.copyProperties(item, northBoundRatioDTO);

            String weekFormat = DateUtil.dateWeekFormat(item.getDate());
            northBoundRatioDTO.setDate(weekFormat);
            northBoundRatioDTO.setClose(closeMap.get(weekFormat));

            ret.add(northBoundRatioDTO);
        });

        return ResultGenerator.genSuccessResult(ret.stream().sorted(Comparator.comparing(NorthBoundRatio::getDate)));
    }
}
